import copy

from django.db import models


class BaseManager(models.Manager):
    # 抽象模型管理器基类
    def get_all_valid_fields(self, **filters):
        # 获取self所在类的模型
        model_class = self.model

        # 获取model_class 类的所有有效属性的元组
        attr_str_list = []
        attr_tuple = model_class._meta.get_fields()

        for attr in attr_tuple:
            if isinstance(attr, models.ForeignKey):
                attr_name = '%s_id'%attr.name
            else:
                attr_name = attr.name
            attr_str_list.append(attr_name)

        return attr_str_list

    def get_one_object(self, **filters):
        try:
            obj = self.get(**filters)
        except models.ObjectDoesNotExist:
            obj = None
        return obj

    def create_one_object(self, **kwargs):
        valid_fields = self.get_all_valid_fields()


        kws = copy.copy(kwargs)

        # 去除kwargs 中的无用属性
        for key in kws.items():
            if key[0] not in valid_fields:
                kwargs.pop(key)

        # 获取self所在的类
        model_class = self.model

        # 创建一个model_class对象
        obj = model_class(**kwargs)
        obj.save()

        return obj

    def get_object_list(self, filters={}, order_by=('-pk', )):
        object_list = self.filter(**filters).order_by(*order_by)
        return object_list
